<template>
  <el-dialog
    title="订单表体模板"
    :visible.sync="dialogVisible"
    width="90%"
    :before-close="handleClose"
    class="order-template-dialog"
  >
    <div class="template-content">
      <div class="template-header">
        <el-button type="primary" size="small" @click="addNewTemplate">新增模板</el-button>
      </div>

      <template v-if="templates.length > 0">
        <el-tabs 
          v-model="activeTabName" 
          type="card" 
          closable 
          @tab-remove="removeTemplate"
          class="template-tabs">
          <el-tab-pane
            v-for="template in templates"
            :key="template.id"
            :label="template.name"
            :name="template.id">
            <div class="form-container">
              <el-form 
                :model="template.form" 
                :rules="rules" 
                :ref="'form_' + template.id" 
                label-width="180px" 
                size="small">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="模板名称" prop="templateName">
                      <el-input v-model="template.form.templateName" placeholder="请输入模板名称"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="电商平台代码" prop="ebpCode">
                      <el-input v-model="template.form.ebpCode" placeholder="请输入电商平台代码"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="电商平台名称" prop="ebpName">
                      <el-input v-model="template.form.ebpName" placeholder="请输入电商平台名称"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="电商企业代码" prop="ebcCode">
                      <el-input v-model="template.form.ebcCode" placeholder="请输入电商企业代码"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="电商企业名称" prop="ebcName">
                      <el-input v-model="template.form.ebcName" placeholder="请输入电商企业名称"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="物流企业代码" prop="logisticsCode">
                      <el-input v-model="template.form.logisticsCode" placeholder="请输入物流企业代码"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物流企业名称" prop="logisticsName">
                      <el-input v-model="template.form.logisticsName" placeholder="请输入物流企业名称"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="申报企业代码" prop="agentCode">
                      <el-input v-model="template.form.agentCode" placeholder="请输入申报企业代码"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申报企业名称" prop="agentName">
                      <el-input v-model="template.form.agentName" placeholder="请输入申报企业名称"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="区内企业代码" prop="areaCode">
                      <el-input v-model="template.form.areaCode" placeholder="请输入区内企业代码"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="区内企业名称" prop="areaName">
                      <el-input v-model="template.form.areaName" placeholder="请输入区内企业名称"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="申报海关代码" prop="customsCode">
                      <el-input v-model="template.form.customsCode" placeholder="请输入申报海关代码"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="口岸海关代码" prop="portCode">
                      <el-input v-model="template.form.portCode" placeholder="请输入口岸海关代码"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="账册编号" prop="emsNo">
                      <el-input v-model="template.form.emsNo" placeholder="请输入账册编号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="担保企业编号" prop="assureCode">
                      <el-input v-model="template.form.assureCode" placeholder="请输入担保企业编号"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="运输方式" prop="trafMode">
                      <el-input v-model="template.form.trafMode" placeholder="请输入运输方式"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="起运国(地区)" prop="country">
                      <el-input v-model="template.form.country" placeholder="请输入起运国(地区)"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="保费" prop="insuredFee">
                      <el-input-number 
                        v-model="template.form.insuredFee" 
                        :precision="2" 
                        :step="0.01" 
                        :min="0"
                        placeholder="请输入保费">
                      </el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item>
                  <el-button type="primary" @click="saveTemplate(template.id)">保存模板</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else>
        <div style="padding: 60px 0; background: #fff;">
          <el-empty 
            description="暂无模板" 
            :image-size="200">
          </el-empty>
        </div>
      </template>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getManifestTemplateList, saveManifestTemplate, deleteManifestTemplate } from '@/api/externalGoods'

export default {
  name: 'OrderTemplateDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      activeTabName: '',
      templates: [],
      templateCounter: 0,
      rules: {
        templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
        ebpCode: [{ required: true, message: '电商平台代码不能为空', trigger: 'blur' }],
        ebpName: [{ required: true, message: '电商平台名称不能为空', trigger: 'blur' }],
        ebcCode: [{ required: true, message: '电商企业代码不能为空', trigger: 'blur' }],
        ebcName: [{ required: true, message: '电商企业名称不能为空', trigger: 'blur' }],
        logisticsCode: [{ required: true, message: '物流企业代码不能为空', trigger: 'blur' }],
        logisticsName: [{ required: true, message: '物流企业名称不能为空', trigger: 'blur' }],
        agentCode: [{ required: true, message: '申报企业代码不能为空', trigger: 'blur' }],
        agentName: [{ required: true, message: '申报企业名称不能为空', trigger: 'blur' }],
        areaCode: [{ required: true, message: '区内企业代码不能为空', trigger: 'blur' }],
        areaName: [{ required: true, message: '区内企业名称不能为空', trigger: 'blur' }],
        customsCode: [{ required: true, message: '申报海关代码不能为空', trigger: 'blur' }],
        portCode: [{ required: true, message: '口岸海关代码不能为空', trigger: 'blur' }],
        emsNo: [{ required: true, message: '账册编号不能为空', trigger: 'blur' }],
        assureCode: [{ required: true, message: '担保企业编号不能为空', trigger: 'blur' }],
        trafMode: [{ required: true, message: '运输方式不能为空', trigger: 'change' }],
        country: [{ required: true, message: '起运国（地区）不能为空', trigger: 'blur' }],
        insuredFee: [{ required: true, message: '保费不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.getTemplateList()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    // 获取模板列表
    async getTemplateList() {
      try {
        const res = await getManifestTemplateList()
        if (res.code === 10000) {
          this.templates = res.data.list.map(item => ({
            id: item.id,
            name: item.templateName,
            form: {
              templateName: item.templateName,
              ebpCode: item.ebpCode,
              ebpName: item.ebpName,
              ebcCode: item.ebcCode,
              ebcName: item.ebcName,
              logisticsCode: item.logisticsCode,
              logisticsName: item.logisticsName,
              agentCode: item.agentCode,
              agentName: item.agentName,
              areaCode: item.areaCode,
              areaName: item.areaName,
              customsCode: item.customsCode,
              portCode: item.portCode,
              emsNo: item.emsNo,
              assureCode: item.assureCode,
              trafMode: item.trafMode,
              country: item.country,
              insuredFee: item.insuredFee
            }
          }))
          if (this.templates.length > 0) {
            this.activeTabName = this.templates[0].id
          }
        } else {
          this.$message.error(res.msg || '获取模板列表失败')
        }
      } catch (error) {
        console.error('获取模板列表失败:', error)
        this.$message.error('获取模板列表失败')
      }
    },

    // 创建新模板
    addNewTemplate() {
      const templateId = 'template_' + (++this.templateCounter)
      const newTemplate = {
        id: templateId,
        name: '新模板' + this.templateCounter,
        form: {
          templateName: '新模板' + this.templateCounter,
          ebpCode: '',
          ebpName: '',
          ebcCode: '3210660A0E',
          ebcName: '扬州数贸港跨境电子商务有限公司',
          logisticsCode: '3120980105',
          logisticsName: '上海韵达货运有限公司',
          agentCode: '3210660A0E',
          agentName: '扬州数贸港跨境电子商务有限公司',
          areaCode: '',
          areaName: '',
          customsCode: '',
          portCode: '',
          emsNo: '',
          assureCode: '',
          trafMode: '',
          country: '',
          insuredFee: 0
        }
      }
      this.templates.push(newTemplate)
      this.activeTabName = templateId
    },

    // 删除模板
    removeTemplate(targetName) {
      const template = this.templates.find(t => t.id === targetName)
      if (!template) return

      this.$confirm('确定要删除该模板吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 如果是新建的模板(id是template_开头的),直接从数组中移除
          if (typeof targetName === 'string' && targetName.startsWith('template_')) {
            this.handleRemoveTemplate(targetName)
            return
          }

          // 否则调用删除接口
          const res = await deleteManifestTemplate({ id: targetName })
          if (res.code === 10000) {
            this.handleRemoveTemplate(targetName)
            this.$message.success(res.msg || '删除成功')
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除模板失败:', error)
          this.$message.error('删除模板失败')
        }
      }).catch(() => {})
    },

    // 处理删除模板后的界面更新
    handleRemoveTemplate(targetName) {
      const tabs = this.templates
      let activeName = this.activeTabName
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.id === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.id
            }
          }
        })
      }
      this.activeTabName = activeName
      this.templates = tabs.filter(tab => tab.id !== targetName)
    },

    // 保存模板
    async saveTemplate(templateId) {
      const template = this.templates.find(t => t.id === templateId)
      if (!template) return

      // 获取对应的表单ref
      const formRef = this.$refs['form_' + templateId]
      if (!formRef) {
        this.$message.error('表单不存在')
        return
      }

      try {
        // 验证表单
        await formRef[0].validate()

        // 构造保存的数据
        const saveData = {
          templateName: template.form.templateName,
          ...template.form
        }

        // 如果不是新建的模板,需要带上id
        if (typeof templateId === 'string' && templateId.startsWith('template_')) {
          // 新建模板不需要带id
          delete saveData.id
        } else {
          // 更新模板需要带上id
          saveData.id = templateId
        }

        // 调用保存接口
        const res = await saveManifestTemplate(saveData)
        if (res.code === 10000) {
          this.$message.success(res.msg || '保存成功')
          // 重新获取列表
          await this.getTemplateList()
        } else {
          this.$message.error(res.msg || '保存失败')
        }
      } catch (error) {
        if (error === false) {
          this.$message.error('请填写完整所有必填项')
        } else {
          console.error('保存模板失败:', error)
          this.$message.error('保存模板失败')
        }
      }
    },

    handleClose() {
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.order-template-dialog {
  :deep(.el-dialog__body) {
    padding: 10px 20px;
  }
  
  .template-content {
    min-height: 400px;
  }

  .template-header {
    margin-bottom: 15px;
  }

  .form-container {
    background: #f5f7fa;
    padding: 20px;
    border-radius: 4px;
    margin-top: 20px;
  }

  .template-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 0;
    }
  }
}
</style> 